<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :class="{'mobile-el-dialog-form': showMobilePage}"
    class="small-common-dialog-size"
    width="450px">
    <Title :title="'调整' + dialogName" style="margin-bottom: 16px;" />
    <el-form
      ref="levelInfoForm"
      :model="paramsObj"
      :rules="levelInfoRules"
      :label-width="labelWidth"
      label-position="right"
      class="level-info-form">
      <el-form-item v-if="changeType === LEVEL_CHANGE_TYPE.PERIOD" label="增加欠款账期" prop="accountPeriod">
        <el-input
          :disabled="!canChangeLevelInfo"
          v-model="paramsObj.accountPeriod"
          name="accountPeriod"
          size="small"
          placeholder="请输入"
          oninput="if(value>1000)value=1000;if(value<-1000)value=-1000"
          @input="accountPeriodInput">
          <span slot="suffix" style="margin-right:5px;color:#333;">天</span>
        </el-input>
      </el-form-item>
      <el-form-item v-else-if="changeType === LEVEL_CHANGE_TYPE.LEVEL" label="客户等级" prop="name">
        <el-select
          v-model="paramsObj.name"
          :disabled="!canChangeLevelInfo"
          size="small"
          popper-class="global-select-down">
          <el-option
            v-for="item in clientLevelOptions"
            :key="item.name"
            :label="item.name"
            :value="item.name"
            :disabled="!canSelectLevel(item)" />
        </el-select>
        <el-tooltip class="item" effect="dark" placement="top">
          <div slot="content" style="max-width:200px;">置灰显示的等级表示你无权限调整，若需设置可保存客户后发起申请</div>
          <tipIcon is-diy style="font-size:15px;color:#ccc;"/>
        </el-tooltip>
      </el-form-item>
      <el-form-item v-else label="提高欠款额度" prop="amount">
        <el-input
          v-model="paramsObj.amount"
          :disabled="!canChangeLevelInfo"
          size="small"
          type="number"
          class="width240"
          placeholder="请输入"
          oninput="if(value>999999999)value=999999999;if(value<-999999999)value=-999999999"
          @input="numInputChange($event, 'amount')"/>
      </el-form-item>
    </el-form>
    <div :style="{ marginLeft: labelWidth }">
      <span style="color: #999">无法提高{{ dialogName }}请点击</span>
      <el-button type="text" size="small" style="font-size: 14px; padding: 0" @click="goCustomerAdjustment">
        发起调额申请
      </el-button>
    </div>
    <div class="dialog-footer" style="display: flex; justify-content: center;margin-top:40px;">
      <el-button
        :loading="loading"
        :disabled="!canChangeLevelInfo || !inputIsValid"
        class="search-btn-style ok"
        style="padding: 7px 10px;"
        type="primary"
        @click="toSet">确定</el-button>
      <el-button class="cancel-btn-style" style="width: 80px" @click="handleClose()">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';
import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage from '@/utils/message';
import { setAccountPeriod, editClientLevel, editClientOweAmount, getLevelList } from '@/api/customer';
import { LEVEL_CHANGE_TYPE } from '@/utils/const/customer';

export default {
  components: { Title },
  props: {
    customerId: { // 客户id
      type: String | Number,
      default: ''
    },
    customerName: { // 客户名称
      type: String,
      default: ''
    },
    target: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      LEVEL_CHANGE_TYPE,
      paramsObj: {
        accountPeriod: '',
        name: '',
        amount: ''
      },
      clientLevelOptions: [],
      changeType: LEVEL_CHANGE_TYPE.LEVEL,
      loading: false,
      dialogVisible: false,
      inputParams: {}
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'userInfo': state => state.user.userInfo
    }),
    computedCustomerName() {
      return this.inputParams.customerName || this.customerName;
    },
    computedCustomerId() {
      return this.inputParams.customerId || this.customerId;
    },
    // 调整客户额度/账期权限
    canChangeLevelInfo() {
      return hasRouteAuth('crm:customer:levelInfoStore');
    },
    // 客户调额申请权限
    canCreateCustomerAdjustment() {
      return hasRouteAuth('crm:customerAdjustment:create');
    },
    inputIsValid() {
      const val = this.paramsObj[this.inputKey];
      if (this.inputKey === 'name') return !!val;
      return Number(val) !== 0 && !isNaN(Number(val));
    },
    levelConfig() {
      return {
        [LEVEL_CHANGE_TYPE.LEVEL]: {
          key: 'name',
          labelWidth: '90px',
          api: editClientLevel,
          title: '等级',
          rule: { name: [{ required: true, trigger: 'change', message: ' ' }] }
        },
        [LEVEL_CHANGE_TYPE.AMOUNT]: {
          key: 'amount',
          labelWidth: '108px',
          api: editClientOweAmount,
          title: '额度',
          rule: { amount: [{ required: true, trigger: 'blur', message: ' ' }] }
        },
        [LEVEL_CHANGE_TYPE.PERIOD]: {
          key: 'accountPeriod',
          labelWidth: '108px',
          api: setAccountPeriod,
          title: '账期',
          rule: { accountPeriod: [{ required: true, trigger: 'blur', message: ' ' }] }
        }
      };
    },
    labelWidth() {
      return this.levelConfig[this.changeType].labelWidth;
    },
    levelInfoRules() {
      return this.levelConfig[this.changeType].rule;
    },
    dialogName() {
      return this.levelConfig[this.changeType].title;
    },
    inputKey() {
      return this.levelConfig[this.changeType].key;
    },
    storeApi() {
      return this.levelConfig[this.changeType].api;
    }
  },
  created() {},
  methods: {
    // 客户等级
    queryClientLevel() {
      getLevelList().then(res => {
        const result = res && res.data || [];
        result.forEach(item => {
          item.label = item.name;
          item.value = item.name;
        });
        this.clientLevelOptions = res && res.data || [];
      }).catch(e => {
        console.log(e);
      });
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs['levelInfoForm'].resetFields();
      this.paramsObj[this.inputKey] = '';
    },
    openDialog(type = LEVEL_CHANGE_TYPE.LEVEL, inputParams = {}) {
      this.inputParams = inputParams;
      if (inputParams.levelName) {
        this.paramsObj.name = inputParams.levelName;
      }
      this.changeType = type;
      this.dialogVisible = true;
      if (type === LEVEL_CHANGE_TYPE.LEVEL) {
        this.$nextTick(() => {
          this.queryClientLevel();
        });
      }
    },
    // 等级有设置岗位且不包含当前用户岗位时，不可选
    canSelectLevel(data) {
      if (!data.post || (Array.isArray(data.post) && !data.post.length)) return true;
      return data.post.includes(this.userInfo.post);
    },
    toSet() {
      const params = this.paramsObj;
      params.id = this.computedCustomerId;
      this.loading = true;
      this.storeApi(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          ElMessage.success('设置成功');
          this.handleClose();
          this.$emit('fetchData');
        } else {
          ElMessage.error(res.messasge);
        }
      }).catch((_) => {
        this.loading = false;
      });
    },
    accountPeriodInput(value) {
      if (value == null || value === '') {
        this.paramsObj.accountPeriod = null;
        return;
      }
      this.paramsObj.accountPeriod = value.replace(/[^\-?\d]/g, '').replace(/^\-?0+/g, '');
    },
    numInputChange(text, prop) {
      if (text == null || text === '') {
        this.paramsObj[prop] = null;
        return;
      }
      let str = text.replace(/[^\-?\d.]/g, ''); // 只允许正负数字
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(-?\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      this.paramsObj[prop] = str;
    },
    goCustomerAdjustment() {
      if (!this.canCreateCustomerAdjustment) {
        this.$message.warning(`暂无客户调额申请权限，请联系管理员添加~`);
        return;
      }
      if (this.target === '_blank') {
        const url = this.$router.resolve({
          name: 'customerAdjustmentCreate',
          query: {
            applyType: this.changeType,
            from: 'list',
            customerId: this.computedCustomerId,
            customerName: this.computedCustomerName
          }
        });
        window.open(url.href, '_blank');
      } else {
        this.handleClose();
        this.$router.push({
          name: 'customerAdjustmentCreate',
          query: {
            applyType: this.changeType,
            customerId: this.computedCustomerId,
            customerName: this.computedCustomerName
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.level-info-form {
  &::v-deep {
    .el-form-item  {
      .el-input {
        height: 30px;
        width: 240px;
      }
    }
    .is-required {
      margin-bottom: 6px !important;
    }
  }
}
.mobile-el-dialog-form {
  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
  }
}
</style>
